//
// Created by ziya on 22-9-7.
//

#include "../include/common.h"

char* open_stream(char* filepath, int* p_filesize) {
    FILE* file = NULL;
    uint filesize = 0;

    /* 打开文件 */
    if (NULL == (file = fopen(filepath, "rb"))) {
        perror("fopen fail");

        exit(1);
    }

    /* 获取文件字节数 */
    if (0 != fseek(file, 0, SEEK_END)) {
        perror("fseek fail");

        exit(1);
    }

    filesize = (int)ftell(file);
    if (-1 == filesize) {
        perror("ftell fail");

        exit(1);
    }

    // 把文件大小传出
    *p_filesize = filesize;

    // 申请内存,存储文件内容
    char* content = (char*)calloc(filesize, 1);
    if (NULL == content) {
        perror("申请内存失败");

        exit(-1);
    }

    /* 将文件内容读入内存 */
    fseek(file, 0, SEEK_SET);

    fread(content, sizeof(char), filesize, file);

    fclose(file);

    return content;
}
